package com.fotoloka.services.impl;

import static com.googlecode.javacv.cpp.opencv_highgui.cvCreateCameraCapture;
import static com.googlecode.javacv.cpp.opencv_highgui.cvGrabFrame;
import static com.googlecode.javacv.cpp.opencv_highgui.cvReleaseCapture;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.fotoloka.exceptions.DispositivoException;
import com.fotoloka.services.DispositivoService;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.cpp.opencv_highgui.CvCapture;

public class DispositivoImpl implements DispositivoService {

	private final static String[] LIBS = { "cv210.dll", "cvaux210.dll",
			"cxcore210.dll", "cxts210.dll", "highgui210.dll", "ml210.dll" };

	private List<Integer> dispositivos = new ArrayList<Integer>();

	@Override
	public void carregarDispositivos() throws DispositivoException {
		File faPath = new File("dll");
		System.out.println(faPath.getAbsolutePath());
		System.setProperty("jna.library.path", faPath.getAbsolutePath());

		try {
			prepareLibraries(faPath);
			discoverDevices();
			if (dispositivos.size() == 0) {
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}
	
	@Override
	public List<Integer> getDispositivos() {
		return dispositivos;
	}

	public void discoverDevices() {
		for (int i = 0; i < 10; i++) {
			CvCapture cap = null;
			try {
				cap = cvCreateCameraCapture(i);
				int res = cvGrabFrame(cap);
				if (res > 0)
					dispositivos.add(i);
				System.out.println("Device " + i + ": " + res);
			} finally {
				if (cap != null) {
					cvReleaseCapture(cap);
				}
			}
		}
	}

	public boolean prepareLibraries(File localPath) throws Exception {
		if (localPath.exists()) {
			boolean libMissing = false;
			for (String lib : LIBS) {
				File libFile = new File(localPath.getAbsolutePath()
						+ File.separator + lib);
				if (!libFile.exists()) {
					libMissing = true;
					break;
				}
			}
			return !libMissing;
		}
		return false;
	}

}
